/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package im.clusterhead;

import im.general.AbstractListenBehaviour;
import im.general.Config;
import jade.core.AID;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.util.Logger;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;

/**
 *
 * @author Gnaskky
 */
public class ClusterUnjoinServerBehaviour extends AbstractListenBehaviour {

    private ClusterHeadAgent ch;

    ClusterUnjoinServerBehaviour(ClusterHeadAgent ch) {
        this.ch = ch;
        ACLMessage wrap_msg = new ACLMessage( ACLMessage.PROPAGATE );
        wrap_msg.addUserDefinedParameter( Config.IM_MSG_TYPE, Config.SRVC_UNJOIN_NOTIFY_MSG);
        this.mt = MessageTemplate.MatchCustom(wrap_msg, true);
    }

    @Override
    protected void handleMessage(ACLMessage in_msg) {
        try {

            String mn = in_msg.getUserDefinedParameter(Config.OLD_MN_NAME);

            if( Config.TRACE_LVL > Config.ULTRA_TR_LVL )
                System.out.println("[ClusterUnjoinServer]\tSRVC_UNJOIN_NOTIFY_MSG [MN CH]   "
                        + mn.split("@")[0] + "\t" + ch.getLocalName());

            if( mn != null && ch.getNodeInfo(mn) != null ) {

                ch.removeNode(mn);

                // Checking Clusterize Conditions
                if (ch.checkShrinkConditions() ) {
                    this.shrink();
                }
            }

        } catch (Exception ex) {
            Logger.getLogger(ClusterJoinServerBehaviour.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
    }

    private void shrink() {
        try {
            //System.out.println("[ClusterUnjoinServer]\tSHRINKING ->\t" + ch.getLocalName());
            // Notify ES of Shrinking
            ACLMessage ntfy_shrink_msg = new ACLMessage(ACLMessage.INFORM);
            ntfy_shrink_msg.addUserDefinedParameter(Config.IM_MSG_TYPE, Config.CH_SHRINK_NOTIFY_MSG);
            ntfy_shrink_msg.addReceiver(new AID(Config.EVENT_SERVICE_NAME, AID.ISLOCALNAME));
            ntfy_shrink_msg.setContentObject(new Vector(ch.getNodesList()));
            ch.sendMessage(ntfy_shrink_msg);
            //takes down the agent
            ch.doDelete();
        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(ClusterUnjoinServerBehaviour.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
    }



}